package kr.hkit.androidcomplete02.ch16;

import kr.hkit.androidcomplete02.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class OrderDialog extends Activity implements CustomDialogFragment.NoticeDialogListener{
	TextView tv;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch16_dialogex);
		
		tv = (TextView) findViewById(R.id.ch16_dialog_tv);
	}
	
	public void mOnClick(View v){
		Bundle args = new Bundle();
		args.putString("title", "주문 정보를 입력하시오.");
		
		CustomDialogFragment cFrg = new CustomDialogFragment();
		cFrg.setArguments(args);
		cFrg.setCancelable(false);
		cFrg.show(getFragmentManager(), "dialog");
	}

	public void onDialogClick(DialogFragment frg, String res) {
		tv.setText(res);
	}
}

class CustomDialogFragment extends DialogFragment{
	NoticeDialogListener mListener;
	Bundle bundle;
	
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mListener = (NoticeDialogListener) activity;
	}
	
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		bundle = getArguments();
		LayoutInflater inflater = getActivity().getLayoutInflater();
		final LinearLayout linear = (LinearLayout) inflater.inflate(R.layout.ch16_order, null);
		
		return new AlertDialog.Builder(getActivity())
			.setIcon(R.drawable.ic_launcher)
			.setTitle(bundle.getString("title"))
			.setView(linear)
			.setPositiveButton("확인", new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					EditText product = (EditText) linear.findViewById(R.id.ch16_order_product);
					EditText cnt = (EditText) linear.findViewById(R.id.ch16_order_cnt);
					CheckBox paymethod = (CheckBox) linear.findViewById(R.id.ch16_order_check);
					
					StringBuilder sb = new StringBuilder("주문 정보\n");
					sb.append(product.getText()+ " ");
					sb.append(cnt.getText() + "개 ");
					sb.append(paymethod.isChecked()?"착불결제":"");
					mListener.onDialogClick(CustomDialogFragment.this, sb.toString());
				}
			})
			.setNegativeButton("취소", new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					mListener.onDialogClick(CustomDialogFragment.this, "주문을 취소했습니다.");
				}
			})
			.create();
	}
	
	public interface NoticeDialogListener{
		public void onDialogClick(DialogFragment frg, String res);
	}
}